#This file is having the column transform specific methods. These transforms include both the 
#size/datatype transforms and the split column transforms. 
#The parameter row is the row of a CSV file.

 #Based on the first option in every row of the CSV file this method decides between splitting and transforming a column.
 def perform_transform
      new_connection = create_new_connection  
      FasterCSV.foreach("column_transform_config.csv") do |row|
            if row[0] == "transform_column"
                transform_columns(row,new_connection)
            elsif row[0] == "split_column"	
                split_columns(row,new_connection)
            end	
      end	
 end


 # This method is the implementation of the column split. It is splitting a given column into columns mentioned in the config files. It does not split the data however.
 def split_columns(row,new_connection)
      for field_counter in 3..row.length-1
          column_struc = get_the_col_spec_for_single_col(row[2],row[1],new_connection)
          new_connection.query("ALTER TABLE #{row[1]} ADD #{row[field_counter]}_splitted #{column_struc}")
      end
 end	 

 
 #This is the main method for the size and data related transforms.  row[3] will have the column specs viz datatype and size. 
 #This method is now handling all the four possible conditions: dataype/size provided, datatype/size not provided.
 def transform_columns(row,new_connection)
        if row[3] == nil || row[3] == ' '
            transform_query_string = row[2]+" "+row[2]
        else	
            transform_query_string = row[2]+" "+row[3]
        end	
        col_specs = get_the_col_spec_for_single_col(row[2], row[1],new_connection)
        col_specs = col_specs.split('(')
        if row[4] == nil 
            col_datatype = col_specs[0]	
        else
            col_datatype = row[4] 
        end
        if row.length == 4 || row.length == 5
            col_size = col_specs[1]
            col_size[col_size.length-1]=''
        else
            col_size = row[5] 
        end
        new_connection.query("ALTER TABLE #{row[1]} CHANGE #{transform_query_string} #{col_datatype.upcase}(#{col_size.to_i})")
 end	 


 #This method is creating the config file template for the column transforms. 
 #Based on the parameter value the template generated is either for split or transform operation.
 def create_column_config_file(column_transform)  
        if  column_transform == "split"
            config_file = File.new("column_split_config.csv","w")	
        else
            config_file = File.new("column_transform_config.csv","w")	
        end		
        config_file.write("transform_column,tablename,original_columnname,new_name,new_datatype,new_size")
        config_file.write("\n")
        config_file.write("split_column,tablename,original_columnname,child_column_first,child_column_second,child_column_third")
 end	